from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from pydantic import ValidationError
from starlette.status import HTTP_404_NOT_FOUND, HTTP_405_METHOD_NOT_ALLOWED

from src import settings
from src.exception import ResponseException
from src.router import crawler
from src import router
from src.exception.handler import method_not_allowed_exception_handler,not_found_exception_handler, response_exception_handler, \
    validation_exception_handler, unhandled_exception_handler
from src import server

# fastapi 生命周期管理
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Load the ML model
    server.init_app()
    yield
    # Clean up the ML model and release the resources
app = FastAPI(lifespan=lifespan)

# 加载路由
app.include_router(router.router)
app.include_router(crawler.router)

# 加载异常处理
app.exception_handler(ResponseException)(response_exception_handler)
app.exception_handler(Exception)(unhandled_exception_handler)
app.exception_handler(HTTP_405_METHOD_NOT_ALLOWED)(method_not_allowed_exception_handler)
app.exception_handler(HTTP_404_NOT_FOUND)(not_found_exception_handler)
app.exception_handler(ValidationError)(validation_exception_handler)
app.exception_handler(RequestValidationError)(validation_exception_handler)


if __name__ == "__main__":
    uvicorn.run(app, host=settings.API_HOST, port=settings.API_PORT)